﻿// Original author contact info: Owen Emlen (owene_1998@yahoo.com)
// Note: other individuals may also have contributed to this code
// Project hosted on CodePlex.com as of 1/10/2009 at http://wpfimageviewer.codeplex.com
using System;
using System.Collections.Specialized;
using System.ComponentModel;
using System.IO;
using AForge.Imaging;
using BrainTechLLC;
using BrainTechLLC.FilterExtensions;
using ImageAppDataModels;
using ImageAppViewModels;
using System.Windows.Threading;

namespace WpfImageDuplicates
{
    public class FilterCollectionHandler : WpfImageDuplicates.IFilterCollectionHandler
    {
        protected Window1 _parentWindow;

        public FilterCollectionViewModel _currentFilterCollection;
        public FilterCollectionCollectionViewModel _filterCollections;
        public FilterCollectionViewModel _blurFilters1;
        public FilterCollectionViewModel _blurFilters2;
        public FilterCollectionViewModel _differenceFilters1;
        public FilterCollectionCollection _filters;
        public string FilterCollectionForSimilarityName;

        public FilterCollectionHandler(Window1 parentWindow)
        {
            _parentWindow = parentWindow;
        }

        public void SaveData()
        {
            _filterCollections.Save(FilePaths._filterSave);
            _blurFilters1.Save(FilePaths._filterBlur1Save);
            _blurFilters2.Save(FilePaths._filterBlur2Save);
            _differenceFilters1.Save(FilePaths._filterCompareSave);
        }

        public void VerifyOneFilterCollectionExists()
        {
            if (_filterCollections.Count == 0)
            {
                _filterCollections.AddFilterCollection(new FilterCollection() { CollectionName = "New Filter Collection" });
            }
        }

        public FilterCollectionViewModel FindFilterCollection(string name)
        {
            for (int n = 0; n < _filterCollections.Count; n++)
            {
                var fc = _filterCollections[n];
                if (fc.CollectionName.Equals(name, StringComparison.OrdinalIgnoreCase))
                {
                    return fc;
                }
            }

            return null;
        }

        public void SetFilterCollection()
        {
            FilterCollectionViewModel found = null;

            if (!string.IsNullOrEmpty(Settings.Values.CurrentFilterCollectionName))
            {
                found = this.FindFilterCollection(Settings.Values.CurrentFilterCollectionName);

                if (found != null)
                {
                    this.CurrentFilterCollection = found;

                    _parentWindow.Dispatcher.BeginInvoke(
                        new VoidDelegate(() => { _parentWindow.CollectionOfFilterCollections.cboUserDefined.SelectedItem = found.CollectionName; }),
                        DispatcherPriority.ApplicationIdle);
                }
            }

            if (found == null)
            {
                this.CurrentFilterCollection = this._filterCollections[0];
            }
        }

        public FilterCollectionViewModel CurrentFilterCollection
        {
            get
            {
                if (_currentFilterCollection == null)
                {
                    if (_filterCollections.Count == 0)
                    {
                        _filterCollections.AddFilterCollection(new FilterCollection() { CollectionName = "New Filter Collection" });
                    }

                    CurrentFilterCollection = _filterCollections[0];
                }

                return _currentFilterCollection;
            }
            set
            {
                if (_currentFilterCollection != value)
                {
                    DisconnectFilterCollectionEvents(_currentFilterCollection);
                    _currentFilterCollection = value;
                    ConnectFilterCollectionEvents(_currentFilterCollection);

                    Window1.MainWindow.SetCurrentFilterCollection(_currentFilterCollection);
                }
            }
        }

        private void ConnectFilterCollectionEvents(FilterCollectionViewModel vm)
        {
            if (vm == null)
                return;

            vm.CollectionChanged += new NotifyCollectionChangedEventHandler(_filterCollection_CollectionChanged);
            vm.GenerationChanged += new EventHandler<NotifyCollectionChangedEventArgs>(_filterCollection_GenerationChanged);
            vm.WantFilterThumbnailsChanged += new EventHandler(_filterCollection_WantFilterThumbnailsChanged);
            vm.WantHighQualityThumbsChanged += new EventHandler(_filterCollection_WantHighQualityThumbsChanged);
        }

        private void DisconnectFilterCollectionEvents(FilterCollectionViewModel vm)
        {
            if (vm == null)
                return;

            vm.CollectionChanged -= _filterCollection_CollectionChanged;
            vm.GenerationChanged -= _filterCollection_GenerationChanged;
            vm.WantFilterThumbnailsChanged -= _filterCollection_WantFilterThumbnailsChanged;
            vm.WantHighQualityThumbsChanged -= _filterCollection_WantHighQualityThumbsChanged;
        }

        private void _filterCollection_WantHighQualityThumbsChanged(object sender, EventArgs e)
        {
            _parentWindow.FileImageCollectionViewModels.ForEach(o => o.InvalidateAllThumbnails(false));
        }

        private void _filterCollection_WantFilterThumbnailsChanged(object sender, EventArgs e)
        {
            _parentWindow.FileImageCollectionViewModels.ForEach(o => o.InvalidateAllThumbnails(false));
        }

        public void OnFiltersGenerationsChanges(bool refreshFiles, bool forceThumbRefresh)
        {
            _parentWindow.FileImageCollectionViewModels.ForEach(o => o.MarkEverythingDirty(Settings.Values.WantFilterThumbnails));

            if (Settings.Values.WantFilterThumbnails || forceThumbRefresh)
            {
                if (_parentWindow._AllFileImageCollectionViewModels != null)
                {
                    _parentWindow.FileImageCollectionViewModels.ForEach(o => o.InvalidateAllThumbnails(false));
                }

                if (refreshFiles)
                {
                    if (_parentWindow._AllFileImageCollectionViewModels != null)
                        _parentWindow.FileImageCollectionViewModels.ForEach(o => o.NeedsRefresh = true);

                    if (_parentWindow._CollectionViews != null)
                        _parentWindow.CollectionViews.ForEach(o => o.ForceRefresh = true);
                }
            }

            if (_parentWindow._FullViewerHandler.IsLoaded)
            {
                if (_parentWindow._FullViewerHandler.Handler.ImageViewModel != null)
                {
                    _parentWindow._FullViewerHandler.Handler.FilterChanged();
                    //_parentWindow._FullViewerHandler.Handler.ImageViewModel.FileImage.MarkFilteredImageDirty();
                    _parentWindow._FullViewerHandler.Handler.ImageViewModel.NotifyImageChanged();
                }
            }
        }

        private void _filterCollection_GenerationChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            OnFiltersGenerationsChanges(e != null, false);
        }

        private void _filterCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            OnFiltersGenerationsChanges(false, false);
        }


        public void LoadBlur2Filters()
        {
            try
            {
                DetermineBlur._blurFilterCollection2 = FilterCollection.Load(FilePaths._filterBlur2Save);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            if (DetermineBlur._blurFilterCollection2 == null)
            {
                DetermineBlur._blurFilterCollection2 = DefaultFilterCollections.CreateDefaultBlur2Filters();
            }

            _blurFilters2 = new FilterCollectionViewModel(DetermineBlur._blurFilterCollection2);
        }

        public void LoadBlur1Filters()
        {
            try
            {
                DetermineBlur._blurFilterCollection1 = FilterCollection.Load(FilePaths._filterBlur1Save);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            if (DetermineBlur._blurFilterCollection1 == null)
            {
                DetermineBlur._blurFilterCollection1 = DefaultFilterCollections.CreateDefaultBlur1Filters();
            }

            _blurFilters1 = new FilterCollectionViewModel(DetermineBlur._blurFilterCollection1);
        }

        public void LoadComparisonFilters()
        {
            try
            {
                DetermineSimilarity._similarityFilterCollection = FilterCollection.Load(FilePaths._filterCompareSave);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            if (DetermineSimilarity._similarityFilterCollection == null)
            {
                DetermineSimilarity._similarityFilterCollection = DefaultFilterCollections.CreateDefaultCompareFilters();
            }

            _differenceFilters1 = new FilterCollectionViewModel(DetermineSimilarity._similarityFilterCollection);
        }

        public void LoadUserDefinedFilters()
        {
            FilterCollectionCollection filters = null;

            try
            {
                filters = FilterCollectionCollection.Load(FilePaths._filterSave);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            if (filters == null)
            {
                filters = new FilterCollectionCollection();
            }

            _filters = filters;
            _filterCollections = new FilterCollectionCollectionViewModel(_filters);
        }

        public void LoadFilters()
        {
            this.LoadUserDefinedFilters();
            this.LoadComparisonFilters();
            this.LoadBlur1Filters();
            this.LoadBlur2Filters();
        }

        public void LoadFilterForSimilarity()
        {
            FilterCollection fc = FilterCollection.Load(Properties.Resources.FilterForSimilarity);
            if (fc != null)
            {
                FilterCollectionForSimilarityName = fc.CollectionName;
                if (!this._filterCollections.ContainsFilterName(fc.CollectionName))
                {
                    this._filterCollections.AddFilterCollection(fc);
                }
            }
        }

    }
}
